<template>
  <div class="data-check-container">
    <!-- 地图组件 -->
    <Map
        ref="mapRef"
        :initialCenter="initialCenter"
        :initialZoom="initialZoom"
        @map-loaded="onMapLoaded"
        @marker-click="onMarkerClick"
    />

    <!-- 数据面板 -->
    <DataPanel
        v-if="activePoint"
        :point="activePoint"
        @close="closePanel"
        @prev-image="handlePrevImage"
        @next-image="handleNextImage"
        @add-comment="addComment"
    />

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>加载数据中...</span>
    </div>
  </div>
</template>

<script>
import Map from './Map.vue'
import DataPanel from './DataPanel.vue'
import { ref, onMounted } from 'vue'
import { Loading } from '@element-plus/icons-vue'
import { convertCoordinate } from '../utils/baiduConvert.js'

export default {
  components: {
    Map,
    DataPanel,
    Loading
  },
  setup() {
    const mapRef = ref(null)
    const activePoint = ref(null)
    const loading = ref(true)
    const initialCenter = ref({ lng: 116.404, lat: 39.915 }) // 北京中心点
    const initialZoom = ref(12)

    // 示例数据 - 使用WGS84坐标
    const sampleData = ref([
      {
        id: 'p1',
        name: '天安门广场',
        lng: 116.3907, // WGS84经度
        lat: 39.9169,  // WGS84纬度
        images: [
          { id: 'img1', url: 'https://inews.gtimg.com/om_bt/O1BQXUf5nLKV1RgQJJTKV8-dXRonoCmOB_H2Dtwn1NOykAA/0', title: '天安门正面' },
          { id: 'img2', url: 'https://img2.baidu.com/it/u=3881523492,2887810075&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667', title: '人民英雄纪念碑' },
          { id: 'img3', url: 'https://q7.itc.cn/q_70/images03/20240520/2e61e4707d6f46a08df9b18dc7a05ba3.jpeg', title: '天安门夜景' }
        ],
        comments: [
          { id: 'c1', user: '旅游达人小王', avatar: 'https://randomuser.me/api/portraits/men/1.jpg', content: '非常壮观的历史建筑，值得一看！', time: '2023-05-12 14:30' },
          { id: 'c2', user: '摄影爱好者小李', avatar: 'https://randomuser.me/api/portraits/women/2.jpg', content: '夜景拍摄效果特别好，建议傍晚去', time: '2023-05-10 09:45' }
        ]
      },
      {
        id: 'p2',
        name: '故宫博物院',
        lng: 116.3974,
        lat: 39.9172,
        images: [
          { id: 'img4', url: 'https://bkimg.cdn.bcebos.com/pic/29381f30e924b899a901efd50e4f0a950a7b0308588e', title: '太和殿' }
        ],
        comments: []
      }
    ])

    // 地图加载完成
    const onMapLoaded = async () => {
      try {
        await addMarkersToMap()
        loading.value = false
      } catch (error) {
        console.error('添加标记失败:', error)
        loading.value = false
      }
    }

    // 添加标记到地图
    const addMarkersToMap = async () => {
      for (const point of sampleData.value) {
        try {
          const converted = await convertCoordinate(point.lng, point.lat);
          // 直接调用 addMarker，不传 icon 参数
          mapRef.value.addMarker(converted.lng, converted.lat, point.name, {
            pointId: point.id // 仅保留必要参数
          });
        } catch (error) {
          console.error(`添加标记失败(${point.name}):`, error);
        }
      }
    };

    // 创建自定义图标
    const createCustomIcon = (hasImages) => {
      const color = hasImages ? '#1890ff' : '#ff4d4f';

      // 合法格式：返回 BMapGL.Icon 实例
      return new BMapGL.Icon(
          // 图标SVG（或图片URL）
          `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 28 28">
      <circle cx="14" cy="14" r="12" fill="${color}" stroke="white" stroke-width="2"/>
      <circle cx="14" cy="14" r="6" fill="white"/>
    </svg>`,
          new BMapGL.Size(28, 28), // 图标大小
          {
            anchor: new BMapGL.Size(14, 14) // 锚点位置（居中）
          }
      );
    };

    // 标记点击事件
    const onMarkerClick = (pointId) => {
      const point = sampleData.value.find(p => p.id === pointId)
      if (point) {
        activePoint.value = {
          ...point,
          currentImageIndex: 0 // 初始化当前图片索引
        }
      }
    }

    // 关闭面板
    const closePanel = () => {
      activePoint.value = null
    }

    // 切换图片
    const handlePrevImage = () => {
      if (!activePoint.value) return
      const images = activePoint.value.images
      if (images.length < 2) return

      const currentIndex = activePoint.value.currentImageIndex || 0
      const newIndex = (currentIndex - 1 + images.length) % images.length
      activePoint.value.currentImageIndex = newIndex
    }

    const handleNextImage = () => {
      if (!activePoint.value) return
      const images = activePoint.value.images
      if (images.length < 2) return

      const currentIndex = activePoint.value.currentImageIndex || 0
      const newIndex = (currentIndex + 1) % images.length
      activePoint.value.currentImageIndex = newIndex
    }

    // 添加评论
    const addComment = (comment) => {
      if (!activePoint.value) return

      const newComment = {
        id: `c${Date.now()}`,
        user: '当前用户',
        avatar: 'https://randomuser.me/api/portraits/men/3.jpg',
        content: comment,
        time: new Date().toLocaleString()
      }

      if (!activePoint.value.comments) {
        activePoint.value.comments = []
      }

      activePoint.value.comments.unshift(newComment)

      // 更新sampleData中的数据
      // const pointIndex = sampleData.value.findIndex(p => p.id === activePoint.value.id)
      // if (pointIndex !== -1) {
      //   sampleData.value[pointIndex].comments.unshift(newComment)
      // }
    }


    return {
      mapRef,
      activePoint,
      loading,
      initialCenter,
      initialZoom,
      onMapLoaded,
      onMarkerClick,
      closePanel,
      handlePrevImage,
      handleNextImage,
      addComment
    }
  }
}
</script>

<style scoped>
.data-check-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.8);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #666;
}

.loading-icon {
  font-size: 36px;
  margin-bottom: 15px;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
